﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.ComponentModel;

namespace D20RpgCommon.Util
{
    public class ObservableProperty<T> : INotifyPropertyChanged
    {
        protected T _value;
        private bool _canNotify = true;

        public ObservableProperty()
        {
            Changed += (s, e) =>
                PropertyChanged(this, new PropertyChangedEventArgs("Value"));
        }

        public ObservableProperty(T initialValue)
            : this()
        {
            _value = initialValue;
        }

        public T Value
        {
            get { return _value; }
            set
            {
                if ((_value == null && value != null)
                    || (_value != null && !_value.Equals(value)))
                {
                    _value = value;
                    if (_canNotify)
                    {
                        ForceChangedEvent();
                    }
                }
            }
        }

        public event PropertyChangedEventHandler PropertyChanged = delegate { };

        public event EventHandler<ValueChangedEventArgs<T>> Changed = delegate { };

        /// <summary>
        ///     Does two-way binding between two observable properties
        /// </summary>
        /// <param name="otherProperty"></param>
        public void BindToProperty(ObservableProperty<T> otherProperty)
        {
            // Initialize the value
            this.Value = otherProperty.Value;

            // Establish change listeners to keep properties in-sync
            otherProperty.Changed += (s, args) => this.Value = args.Value;
            this.Changed += (s, args) => otherProperty.Value = args.Value;
        }

        public void DisableNotifications()
        {
            _canNotify = false;
        }

        public void EnableNotifications()
        {
            _canNotify = true;
        }

        public void ForceChangedEvent()
        {
            Changed(this, new ValueChangedEventArgs<T>(_value));
        }
    }
}
